<template>
  <a-spin :spinning="confirmLoading">
   <a-tabs v-model:activeKey="resume"  animated style="margin-left: 20px">
      <a-tab-pane tab="人员台账" key="resume" :forceRender="true" >
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="12">
          <a-form-item label="供应商" v-bind="validateInfos.supplier">
	          <j-search-select v-model:value="formData.supplier" dict="tm_supplier_manage,supplier_name,id" :disabled="disabled" allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="姓名" v-bind="validateInfos.realName">
            <a-input v-model:value="formData.realName" placeholder="请输入姓名" :disabled="disabled" allowClear></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="职级" v-bind="validateInfos.positionLevel">
	          <j-dict-select-tag v-model:value="formData.positionLevel" dictCode="position_level" placeholder="请选择职级" :disabled="disabled" allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="外包人员电话" v-bind="validateInfos.mobile">
            <a-input v-model:value="formData.mobile" placeholder="请输入外包人员电话" :disabled="disabled" allowClear></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="所属部门" v-bind="validateInfos.departId">
	          <j-search-select v-model:value="formData.departId" dict="sys_depart where org_type<>1,depart_name,id" placeholder="请选择所属部门" :disabled="disabled" allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="项目" v-bind="validateInfos.projectId">
	          <j-search-select v-model:value="formData.projectId" dict="tm_project,project_name,id" placeholder="请选择项目" @change="projectChange" :disabled="disabled" allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="项目经理" v-bind="validateInfos.pmId">
            <j-search-select v-model:value="formData.pmId" dict="sys_user,realname,username" placeholder="请选择项目经理" @change="userChange" :disabled="disabled" allowClear/>
			      <!-- <j-select-user v-model:value="formData.pmId" :disabled="disabled"/> -->
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="项目经理电话" v-bind="validateInfos.pmMobile">
            <a-input v-model:value="formData.pmMobile" placeholder="请输入项目经理电话" :disabled="disabled" allowClear></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="质量对接人" v-bind="validateInfos.testLiaison">
			     <!-- <j-select-user v-model:value="formData.testLiaison" :disabled="disabled"/> -->
           <j-search-select v-model:value="formData.testLiaison" dict="sys_user,realname,username" placeholder="请选择质量对接人" :disabled="disabled" allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="工作地点" v-bind="validateInfos.workPlace">
	          <j-search-select v-model:value="formData.workPlace" dict="tm_work_place,work_place,id" placeholder="请选择工作地点" :disabled="disabled" allowClear/>
          </a-form-item>
        </a-col>
    
        <a-col :span="12">
          <a-form-item label="合同开始时间" v-bind="validateInfos.contractStartTime">
		        <a-date-picker placeholder="请选择合同开始时间" v-model:value="formData.contractStartTime" @change="contractStartDateChange" value-format="YYYY-MM-DD"  style="width: 100%" :disabled="disabled" allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="合同结束时间" v-bind="validateInfos.contractEndTime">
		        <a-date-picker placeholder="请选择合同结束时间" v-model:value="formData.contractEndTime" @change="contractEndDateChange" value-format="YYYY-MM-DD"  style="width: 100%" :disabled="disabled" allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="入项时间" v-bind="validateInfos.entryTime">
		        <a-date-picker placeholder="请选择入项时间" v-model:value="formData.entryTime" value-format="YYYY-MM-DD" @change="entryDateChange" style="width: 100%" :disabled="disabled" allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="离项时间" v-bind="validateInfos.departureTime">
		        <a-date-picker placeholder="请选择离项时间" v-model:value="formData.departureTime" value-format="YYYY-MM-DD" @change="departureDateChange" style="width: 100%" :disabled="disabled" allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="预警日期" v-bind="validateInfos.expireTipTime">
		        <a-date-picker placeholder="请选择预警日期" v-model:value="formData.expireTipTime" value-format="YYYY-MM-DD"  style="width: 100%" :disabled="disabled" allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="订单编号" v-bind="validateInfos.orderNo">
            <a-input v-model:value="formData.orderNo" placeholder="请输入订单编号" :disabled="disabled" allowClear></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="人员简历" v-bind="validateInfos.resumeId">
	          <j-search-select v-model:value="formData.resumeId" dict="tm_resume,real_name,id" placeholder="请选择人员简历" :disabled="disabled" allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="人员需求" v-bind="validateInfos.positionReqId">
	          <j-search-select ref="refPositionReq" v-model:value="formData.positionReqId" placeholder="请选择人员需求" :dict="positionReqDict"  :disabled="disabled" allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="面试评价" v-bind="validateInfos.interviewEvaluate">
	          <a-textarea v-model:value="formData.interviewEvaluate" :rows="4" placeholder="请输入面试评价" :disabled="disabled" allowClear/>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
 </a-tab-pane>
 <a-tab-pane tab="人员评价" key="departureEvaluateRecord" :forceRender="true">
    <j-vxe-table
      :keep-source="true"
      resizable
      ref="departureEvaluateRecordTableRef"
      :loading="departureEvaluateRecordTable.loading"
      :columns="departureEvaluateRecordTable.columns"
      :dataSource="departureEvaluateRecordTable.dataSource"
      :height="340"
      :disabled="true"
      :rowNumber="true"
      :rowSelection="true"
      :toolbar="false"/>
  </a-tab-pane>
  </a-tabs>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
  import JSelectUser from '/@/components/Form/src/jeecg/components/JSelectUser.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate,queryDepartureEvaluateRecordListByMainId,getUserInfo } from '../OutsourcePersonAccount.api';
  import { Form } from 'ant-design-vue';
  import {departureEvaluateRecordColumns} from '../OutsourcePersonAccount.data';


  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: ()=>{} },
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const refPositionReq = ref();
  const positionReqDict = ref<string>();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    supplier: '',
    realName: '',
    positionLevel: '',
    mobile: '',
    departId: '',
    projectId: '',
    pmId: '',
    pmMobile: '',
    testLiaison: '',
    workPlace: '',
    orderNo: '',
    contractStartTime: '',
    contractEndTime: '',
    entryTime: '',
    departureTime: '',
    expireTipTime: '',
    resumeId: '',
    positionReqId:'',
    interviewEvaluate: '',
  });

  const formRecordData = reactive<Record<string, any>>({
    supplier: '',
    realName: '',
    mobile: '',
    resumeId: '',
    departId: '',
  });
  const { createMessage } = useMessage();
  // const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  // const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const labelCol = ref<any>({style: { width: '100px' }})
  const wrapperCol = ref<any>({});
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = {
    supplier: [{ required: true, message: '请输入供应商!'},],
    realName: [{ required: true, message: '请输入姓名!'},],
    positionLevel: [{ required: true, message: '请输入职级!'},],
    // mobile: [{ required: true, message: '请输入外包人员电话!'}, { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码!'},],
    projectId: [{ required: true, message: '请选择项目!'},],
    pmId: [{ required: true, message: '请选择项目经理!'},],
    pmMobile: [{ required: true, message: '请输入项目经理电话!'}, { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码!'},],
    testLiaison: [{ required: true, message: '请选择质量对接人!'},],
    workPlace: [{ required: true, message: '请输入工作地点!'},],
    // orderNo: [{ required: true, message: '请输入订单编号!'},],
    contractStartTime: [{ required: true, message: '请输入合同开始时间!'},],
    contractEndTime: [{ required: true, message: '请输入合同结束时间!'},],
    entryTime: [{ required: true, message: '请输入入项时间!'},],
    departureTime: [{ required: true, message: '请输入离项时间!'},],
    expireTipTime: [{ required: true, message: '请输入预警日期!'},],
    resumeId: [{ required: true, message: '请选择简历!'},],
    positionReqId: [{ required: true, message: '请选择人员需求!'},],

  };
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  const departureEvaluateRecordTableRef = ref();
  const departureEvaluateRecordTable = reactive<Record<string, any>>({
    loading: false,
    columns: departureEvaluateRecordColumns,
    dataSource: []
  });

  function userChange(item) {
        getUserInfo(item).then((res) => {
       formData.pmMobile = res.phone
    });
  }

  function projectChange(item) {
    formData.projectId=item
    // positionReqDict.value = "tm_position_req where project_id='"+item+"',position_req_no,id"
    positionReqDict.value = "tm_position_req where (req_status=2 or req_status=5) and project_id='"+item+"',position_req_no,id"

    refPositionReq.value.initSelectValue();
  }

  function loadPostionReqSelect() {
    // positionReqDict.value = "tm_resume_lock_record,position_req_no,position_req_id"
    positionReqDict.value = "tm_position_req,position_req_no,id"
    refPositionReq.value.initSelectValue();
  }
  /**
   * 新增
   */
  function add() {
    // loadPostionReqSelect();
    // edit({});
    resetFields();
     departureEvaluateRecordTable.dataSource = [];
  }

  function personEntry(record) {
    // loadPostionReqSelect();
    formRecordData.supplier = record.supplier;
    formRecordData.realName = record.realName;
    formRecordData.resumeId = record.id;
    formRecordData.mobile = record.mobile;
    formRecordData.departId = record.departId;
    edit2(formRecordData);
  }

  async function edit2(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData, tmpData);
    });
  }
  function contractStartDateChange(date) {
    console.log('contractStartTimeChange....');
    formData.entryTime = date;
  }

  function contractEndDateChange(date) {
    console.log('contractendTimeChange....');
    formData.departureTime = date;
    // formData.expireTipTime = (date+14);
  }


  /**
   * 编辑
   */
  async function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData, tmpData);
    });
    // //评价数据
    const departureEvaluateRecordDataList = await queryDepartureEvaluateRecordListByMainId(record['resumeId']);
    departureEvaluateRecordTable.dataSource = [...departureEvaluateRecordDataList];
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    await validate();
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


  defineExpose({
    add,
    edit,
    submitForm,
    personEntry,
    departureEvaluateRecordTableRef,
    departureEvaluateRecordTable,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    height: 500px !important;
    overflow-y: auto;
    padding: 14px;
  }
</style>
